#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, glob
import json

# 转为mV,CLHEP::volt = 1e-6
millivolt = 1e-9

# 从文件中读取数据
def get(fp):
	fp.seek(0)
	digi_list = [[] for _ in range(50)]
	trace_list = []
	model = {}
	p = 0
	for l in fp.readlines():
		j = json.loads(l)
		if j["class"] == "G4SipmDigi":
			digi_list[p].append(j)
		if j["class"] == "G4SipmVoltageTraceDigi":
			p = p + 1
			trace_list.append(j)
		if j["class"] == "G4SipmModel":
			model = j
	return digi_list,trace_list,model

if __name__ == "__main__":
	# 获取results目录下最新的txt文件
	with open('voltages.txt', 'w') as outputfile:
		filename = glob.glob('results/*.txt')[-1]
		if len(sys.argv) > 1:
			filename = sys.argv[1]
		# 打开文件
		fp = open(filename)
		digis,traces,model = get(fp)
		# 解析电压轨迹
		for j, trace in enumerate(traces):
			for q, v in enumerate(trace["voltages"]):
				outputfile.write("%f\t" % (v / millivolt))
			outputfile.write("\n")		
	outputfile.close()
	
